var express = require("express");
var router = express.Router();

const usersModel = require("../models/users_module.js");

// 判断是否为注册过的手机号 -- 同时获取该手机号对应的数据信息
router.post("/isRegister", function (req, res, next) {
  const { phone } = req.body;

  usersModel.findOne({ phone: phone }, (err, doc) => {
    if (err) throw err;
    res.json({
      status: 0,
      list: doc,
    });
  });
});

/* 新用户登录添加用户接口. */
router.post("/login", function (req, res, next) {
  const { phone } = req.body;
  // 创建用户实例
  const user = new usersModel({
    phone,
    point: 0,
    deposit: 500,
    level: "普通用户",
    signin: 0,
    haveSign: 0,
    gather: [],
    place: "江干区",
  });
  // 将实例添加到数据库
  user.save((err) => {
    if (err) throw err;
    usersModel.find({ phone: phone }, (err, doc) => {
      if (err) throw err;
      res.json({
        status: 0,
        list: doc,
        msg: "登录成功",
      });
    });
  });
});

router.post("/info", function (req, res, next) {
  const { token } = req.body;
  usersModel.findOne(
    {
      _id: token,
    },
    (err, doc) => {
      if (err) throw err;
      res.json({
        status: 0,
        list: doc,
      });
    }
  );
});

// 添加收藏房源信息
router.post("/collect", function (req, res, next) {
  const { token, gather } = req.body;

  usersModel.updateOne(
    { _id: token },
    {
      gather: gather,
    },
    (err) => {
      if (err) throw err;
      res.json({
        status: 0,
        msg: "收藏成功",
      });
    }
  );
});

module.exports = router;
